package dao

import (
	"encoding/json"
	"time"
	"user_srv/basic/config"
	"user_srv/handler/model"
)

type FriendActivityService struct{}

// PostActivity 保存动态并推送给在线好友，离线好友记录通知
func (s *FriendActivityService) PostActivity(userId int64, content string, images []string) (int64, error) {
	imgs, _ := json.Marshal(images)
	act := &model.XqFriendActivities{UserId: userId, Content: content, Images: string(imgs), CreatedAt: time.Now()}
	if err := act.Create(); err != nil {
		return 0, err
	}

	// 找到用户的好友列表（单向记录）
	var friends []model.XqUserFriends
	if err := config.DB.Where("user_id = ? AND is_active = 1", userId).Find(&friends).Error; err == nil {
		// 构造活动数据
		payload := map[string]interface{}{
			"type":        "friend_activity",
			"activity_id": act.Id,
			"user_id":     userId,
			"content":     content,
			"images":      images,
			"created_at":  act.CreatedAt.Unix(),
		}
		// 向在线好友推送WS，离线好友写通知
		chat := GetChatService()
		for _, f := range friends {
			// WS推送
			_ = chat.SendWSMessage(f.FriendId, payload)
			// 离线通知（Type=3: 好友动态）
			var ns NotificationService
			_ = ns.SendCustomNotification(f.FriendId, 3, "好友动态", content, act.Id)
		}
	}
	return act.Id, nil
}

// GetFeed 拉取好友动态
func (s *FriendActivityService) GetFeed(userId int64, page, pageSize int32) ([]model.XqFriendActivities, int32, error) {
	if page <= 0 {
		page = 1
	}
	if pageSize <= 0 {
		pageSize = 20
	}
	// 收集自己+好友的userId集合
	var rels []model.XqUserFriends
	if err := config.DB.Where("user_id = ? AND is_active = 1", userId).Find(&rels).Error; err != nil {
		return nil, 0, err
	}
	ids := make([]int64, 0, len(rels)+1)
	ids = append(ids, userId)
	for _, r := range rels {
		ids = append(ids, r.FriendId)
	}

	// 查询总数
	var total int64
	if err := config.DB.Model(&model.XqFriendActivities{}).Where("user_id IN (?)", ids).Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	var m model.XqFriendActivities
	list, err := m.ListByUserIds(ids, int(pageSize), int((page-1)*pageSize))
	if err != nil {
		return nil, 0, err
	}
	return list, int32(total), nil
}
